package com.qb.hotelTV.huibuTv;

import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.baidu.duer.botsdk.BotIntent;
import com.qb.hotelTV.Model.VideoModel;
import com.qb.hotelTV.constants.AppConstants;
import com.qb.hotelTV.viewmodel.IndexViewModel;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Map;

/**
 * 百度TV SDK Bot意图处理器 - 优化版
 * 支持ViewModel架构，防止内存泄漏，使用常量管理
 */
public class BotIntentHandler {
    private static final String TAG = AppConstants.LogTags.BOT_INTENT_HANDLER;
    
    private WeakReference<Context> contextRef;
    private WeakReference<MainActivity> activityRef;
    private IndexViewModel viewModel;
    
    public BotIntentHandler(Context context, MainActivity mainActivity, IndexViewModel viewModel) {
        this.contextRef = new WeakReference<>(context);
        this.activityRef = new WeakReference<>(mainActivity);
        this.viewModel = viewModel;
    }
    
    /**
     * 处理Bot意图
     */
    public void handleIntent(BotIntent intent) {
        if (intent == null) {
            Log.w(TAG, "收到空的Bot意图");
            return;
        }
        
        String intentName = intent.getName();
        Map<String, String> slots = intent.getSlots();
        
        Log.d(TAG, "处理Bot意图: " + intentName);
        Log.d(TAG, "意图参数: " + slots);
        
        // 检查Activity是否还存在
        MainActivity activity = activityRef.get();
        if (activity == null || activity.isFinishing()) {
            Log.w(TAG, "Activity已销毁，忽略语音指令");
            return;
        }
        
        switch (intentName) {
            // 播放控制相关
            case AppConstants.INTENT_TV_CONTROL_PLAY:
                handlePlayControl();
                break;
            case AppConstants.INTENT_TV_CONTROL_PAUSE:
                handlePauseControl();
                break;
            case AppConstants.INTENT_TV_CONTROL_STOP:
                handleStopControl();
                break;
                
            // 频道切换相关
            case AppConstants.INTENT_TV_CHANNEL_SWITCH:
                handleChannelSwitch(slots);
                break;
            case AppConstants.INTENT_TV_CHANNEL_UP:
            case AppConstants.INTENT_TV_CHANNEL_NEXT:
                handleChannelUp();
                break;
            case AppConstants.INTENT_TV_CHANNEL_DOWN:
            case AppConstants.INTENT_TV_CHANNEL_PREVIOUS:
                handleChannelDown();
                break;
                
            // 音量控制相关
            case AppConstants.INTENT_TV_VOLUME_UP:
                handleVolumeUp();
                break;
            case AppConstants.INTENT_TV_VOLUME_DOWN:
                handleVolumeDown();
                break;
            case AppConstants.INTENT_TV_VOLUME_MUTE:
                handleVolumeMute();
                break;
                
            // 导航控制相关
            case AppConstants.INTENT_TV_CONTROL_BACK:
                handleBackControl();
                break;
            case AppConstants.INTENT_TV_CONTROL_HOME:
                handleHomeControl();
                break;
            case AppConstants.INTENT_TV_CONTROL_MENU:
                handleMenuControl();
                break;
                
            // 电源控制相关
            case AppConstants.INTENT_TV_POWER_OFF:
                handlePowerOff();
                break;
                
            // 搜索相关
            case AppConstants.INTENT_TV_CONTENT_SEARCH:
                handleContentSearch(slots);
                break;
                
            // 节目查询相关
            case AppConstants.INTENT_TV_PROGRAM_QUERY:
                handleProgramQuery(slots);
                break;
                
            default:
                handleUnknownIntent(intentName, slots);
                break;
        }
    }
    
    /**
     * 播放控制
     */
    private void handlePlayControl() {
        Log.d(TAG, "执行播放控制");
        if (viewModel != null) {
            viewModel.playVideo();
        }
        showToast("语音控制：播放");
    }
    
    /**
     * 暂停控制
     */
    private void handlePauseControl() {
        Log.d(TAG, "执行暂停控制");
        if (viewModel != null) {
            viewModel.pauseVideo();
        }
        showToast("语音控制：暂停");
    }
    
    /**
     * 停止控制
     */
    private void handleStopControl() {
        Log.d(TAG, "执行停止控制");
        if (viewModel != null) {
            viewModel.stopVideo();
        }
        showToast("语音控制：停止");
    }
    
    /**
     * 频道切换
     */
    private void handleChannelSwitch(Map<String, String> slots) {
        Log.d(TAG, "执行频道切换");
        
        if (slots != null && slots.containsKey("channel_name")) {
            String channelName = slots.get("channel_name");
            Log.d(TAG, "切换到频道: " + channelName);
            
            if (viewModel != null) {
                viewModel.selectChannelByName(channelName);
                showToast("切换到频道：" + channelName);
            }
        } else if (slots != null && slots.containsKey("channel_number")) {
            String channelNumber = slots.get("channel_number");
            Log.d(TAG, "切换到频道号: " + channelNumber);
            
            try {
                int channelIndex = Integer.parseInt(channelNumber) - 1; // 转换为索引
                // TODO: 添加按索引选择频道的方法到ViewModel
                showToast("切换到第" + channelNumber + "频道");
            } catch (NumberFormatException e) {
                showToast("无效的频道号：" + channelNumber);
            }
        } else {
            showToast("语音控制：频道切换");
        }
    }
    
    /**
     * 上一频道
     */
    private void handleChannelUp() {
        Log.d(TAG, "执行上一频道");
        if (viewModel != null) {
            viewModel.previousChannel();
        }
        showToast("语音控制：上一频道");
    }
    
    /**
     * 下一频道
     */
    private void handleChannelDown() {
        Log.d(TAG, "执行下一频道");
        if (viewModel != null) {
            viewModel.nextChannel();
        }
        showToast("语音控制：下一频道");
    }
    
    /**
     * 音量+
     */
    private void handleVolumeUp() {
        Log.d(TAG, "执行音量+");
        simulateKeyPress(KeyEvent.KEYCODE_VOLUME_UP);
        showToast("语音控制：音量+");
    }
    
    /**
     * 音量-
     */
    private void handleVolumeDown() {
        Log.d(TAG, "执行音量-");
        simulateKeyPress(KeyEvent.KEYCODE_VOLUME_DOWN);
        showToast("语音控制：音量-");
    }
    
    /**
     * 静音
     */
    private void handleVolumeMute() {
        Log.d(TAG, "执行静音");
        simulateKeyPress(KeyEvent.KEYCODE_VOLUME_MUTE);
        showToast("语音控制：静音");
    }
    
    /**
     * 返回
     */
    private void handleBackControl() {
        Log.d(TAG, "执行返回");
        simulateKeyPress(KeyEvent.KEYCODE_BACK);
        showToast("语音控制：返回");
    }
    
    /**
     * 首页
     */
    private void handleHomeControl() {
        Log.d(TAG, "执行首页");
        simulateKeyPress(KeyEvent.KEYCODE_HOME);
        showToast("语音控制：首页");
    }
    
    /**
     * 菜单
     */
    private void handleMenuControl() {
        Log.d(TAG, "执行菜单");
        simulateKeyPress(KeyEvent.KEYCODE_MENU);
        showToast("语音控制：菜单");
    }
    
    /**
     * 关机
     */
    private void handlePowerOff() {
        Log.d(TAG, "执行关机");
        showToast("语音控制：关机");
        // 这里可以添加关机逻辑
        mainActivity.finish();
    }
    
    /**
     * 内容搜索
     */
    private void handleContentSearch(Map<String, String> slots) {
        Log.d(TAG, "执行内容搜索");
        
        if (slots != null && slots.containsKey("keyword")) {
            String keyword = slots.get("keyword");
            Log.d(TAG, "搜索关键词: " + keyword);
            showToast("搜索：" + keyword);
            // 这里可以添加搜索逻辑
        } else {
            showToast("语音控制：内容搜索");
        }
    }
    
    /**
     * 节目查询
     */
    private void handleProgramQuery(Map<String, String> slots) {
        Log.d(TAG, "执行节目查询");
        showToast("语音控制：节目查询");
        // 这里可以添加节目查询逻辑
    }
    
    /**
     * 处理未知意图
     */
    private void handleUnknownIntent(String intentName, Map<String, String> slots) {
        Log.d(TAG, "收到未知意图: " + intentName);
        showToast("收到语音指令: " + intentName);
    }
    
    /**
     * 根据频道名称切换频道
     */
    private boolean switchToChannelByName(String channelName) {
        ArrayList<VideoModel> videoList = MyApplication.getVideoList(context);
        if (videoList != null) {
            for (int i = 0; i < videoList.size(); i++) {
                VideoModel video = videoList.get(i);
                if (video.getName().contains(channelName)) {
                    MyApplication.setChannelIndex(i);
                    return true;
                }
            }
        }
        
        // 如果没有找到视频列表，尝试默认频道列表
        ArrayList<Channel> channelsList = MyApplication.getChannelsList();
        if (channelsList != null) {
            for (int i = 0; i < channelsList.size(); i++) {
                Channel channel = channelsList.get(i);
                if (channel.getName().contains(channelName)) {
                    MyApplication.setChannelIndex(i);
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * 根据频道索引切换频道
     */
    private boolean switchToChannelByIndex(int channelIndex) {
        ArrayList<VideoModel> videoList = MyApplication.getVideoList(context);
        if (videoList != null && channelIndex >= 0 && channelIndex < videoList.size()) {
            MyApplication.setChannelIndex(channelIndex);
            return true;
        }
        
        ArrayList<Channel> channelsList = MyApplication.getChannelsList();
        if (channelsList != null && channelIndex >= 0 && channelIndex < channelsList.size()) {
            MyApplication.setChannelIndex(channelIndex);
            return true;
        }
        
        return false;
    }
    
    /**
     * 模拟按键操作
     */
    private void simulateKeyPress(int keyCode) {
        if (mainActivity != null) {
            KeyEvent downEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
            KeyEvent upEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
            
            mainActivity.runOnUiThread(() -> {
                mainActivity.dispatchKeyEvent(downEvent);
                mainActivity.dispatchKeyEvent(upEvent);
            });
        }
    }
    
    /**
     * 显示Toast消息
     */
    private void showToast(String message) {
        if (mainActivity != null) {
            mainActivity.runOnUiThread(() -> {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            });
        }
    }
} 